package com.cn.wanxi.controller;

import com.alibaba.fastjson.JSON;
import com.cn.wanxi.entity.MailEntity;
import com.cn.wanxi.entity.ResultEntity;
import com.cn.wanxi.rabbitmq.Sender;
import com.cn.wanxi.redis.RedisUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;

@Controller
public class MailController {
    @Value("${spring.mail.username}")
    private String from;
    /**
     * 邮件发送接口
     */
    @Autowired
    private JavaMailSender mailSender;
    //    @Autowired
//    private MailEntity mailEntity;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 普通的邮件
     *
     * @param mailEntity
     * @return
     */
    @RequestMapping("/simpleMailMessage")
    @ResponseBody
    public ResultEntity simpleMailMessage(MailEntity mailEntity) throws Exception {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(mailEntity.getTo());
        //邮件标题
        message.setSubject(mailEntity.getSubject());
        //邮件内容
        message.setText(mailEntity.getContent());
//        将邮件信息存入redis
        redisUtils.lPush("mailEntityList", mailEntity);
//        将邮件存入es,这里用json的形式插入数据
        addKeyValue(mailEntity);
//        发送消息进入队列
        new Sender().send();
        try {
            mailSender.send(message);
            return new ResultEntity(from, "200", "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return new ResultEntity(from, "400", "发送普通邮件失败");
        }
    }

    /**
     * 插入一条json数据
     *
     * @param mailEntity
     * @throws IOException
     */
    private void addJson(MailEntity mailEntity) throws IOException {
        IndexRequest indexRequest = new IndexRequest("mail");
        indexRequest.id("1");
        String json = JSON.toJSONString(mailEntity);
        indexRequest.source(json, XContentType.JSON);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        //        获取响应数据
        System.out.println(indexResponse);
    }

    /**
     * 插入key-value的形式
     *
     * @param mailEntity
     * @throws IOException
     */
    private void addKeyValue(MailEntity mailEntity) throws IOException {
        IndexRequest indexRequest = new IndexRequest("mail");
        indexRequest.id("1");
        String json = JSON.toJSONString(mailEntity);
        indexRequest.source("to", mailEntity.getTo(), "subject", mailEntity.getSubject(), "content", mailEntity.getContent());
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
//        获取响应数据
        System.out.println(indexResponse);
    }



    @RequestMapping("/mimeMessage")
    @ResponseBody
    public ResultEntity mimeMessage(MailEntity mailEntity) throws MessagingException {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
        //谁发
        minehelper.setFrom(from);
        //谁要接收
        minehelper.setTo(mailEntity.getTos());
        //邮件主题
        minehelper.setSubject(mailEntity.getSubject());
        //邮件内容   true 表示带有附件或html
//        getContent可以些html带样式的内容
        minehelper.setText(mailEntity.getContent(), true);
        try {
            mailSender.send(message);
            return new ResultEntity(from, "200", "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return new ResultEntity(from, "400", "发送普通邮件失败");
        }
    }

    @RequestMapping("/imgMessage")
    @ResponseBody
    public ResultEntity imgMessage(MailEntity mailEntity, MultipartFile multipartFile, String imgHref) throws MessagingException {
//创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            helper.setTo(mailEntity.getTos());
            //邮件主题
            helper.setSubject(mailEntity.getSubject());
            //邮件内容   true 表示带有附件或html
            //邮件内容拼接
            String content =
                    "<html><body><img width='250px' src=\'" + imgHref + "\'>" + mailEntity.getContent()
                            + "</body></html>";
            helper.setText(content, true);
            //蒋 multpartfile 转为file
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            FileSystemResource res = new FileSystemResource(multipartFileToFile);

            //添加内联资源，一个id对应一个资源，最终通过id来找到该资源
            helper.addInline(imgHref, res);
            return new ResultEntity(from, "200", "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return new ResultEntity(from, "400", "发送普通邮件失败");
        }
    }

    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/fileMessage")
    @ResponseBody
    public ResultEntity fileMessage(MailEntity mailEntity, MultipartFile multipartFile) throws MessagingException {
//创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            helper.setTo(mailEntity.getTos());
            //邮件主题
            helper.setSubject(mailEntity.getSubject());
            //邮件内容   true 表示带有附件或html
            helper.setText(mailEntity.getContent(), true);
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            FileSystemResource file = new FileSystemResource(multipartFileToFile);
            String filename = file.getFilename();
            //添加附件
            helper.addAttachment(filename, file);
            mailSender.send(message);
            return new ResultEntity(from, "200", "发送普通邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            return new ResultEntity(from, "400", "发送普通邮件失败");
        }
    }
}
